package cn.changgou.order.controller;

import cn.changgou.entity.Result;
import cn.changgou.entity.StatusCode;
import cn.changgou.entity.TokenDecode;
import cn.changgou.order.pojo.OrderItem;
import cn.changgou.order.service.CartService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.authentication.OAuth2AuthenticationDetails;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.Map;

/*购物车操作*/
@RestController
@RequestMapping(value = "/cart")
public class CartController {

    @Autowired
    private CartService cartService;

    /**
     * 加入购物车
     * 1. 加入购物车数量
     * 2. 商品ID
     */
    @GetMapping(value = "/add")
    public Result add(Integer num, Long id) {
        Map<String, String> userInfo = TokenDecode.getUserInfo();
        System.out.println(userInfo);
        String username = userInfo.get("username");
        // 加入购物车
        cartService.add(id, num, username);
        return new Result(true, StatusCode.OK, "加入购物车成功！");
    }

    /**
     * 购物车列表
     */
    @GetMapping("/list")
    public Result<List<OrderItem>> list() {
        // 用户的令牌信息->解析令牌信息->username
        // 获取用户登录名
        //OAuth2AuthenticationDetails details = (OAuth2AuthenticationDetails) SecurityContextHolder.getContext().getAuthentication().getDetails();
        //String token = details.getTokenValue();
        Map<String, String> userInfo = TokenDecode.getUserInfo();
        System.out.println(userInfo);
        String username = userInfo.get("username");
//        String username = "szitheima";
        // 查询购物车列表
        List<OrderItem> orderItems = cartService.list(username);
        return new Result<>(true, StatusCode.OK, "查询购物车列表成功！", orderItems);
    }
}